package phidgetmotion.gui.util;

import java.awt.Dimension;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class BindingTextBox extends JPanel
{
	private static final long serialVersionUID = 1L;
	private JTextField text;
	private TextDataSource dataSource;
	private boolean update = false;;
	
	private DocumentUpdateListener documentChangeListener = new DocumentUpdateListener()
	{
		@Override
		public void dataChanged()
		{
			if(!update) dataSource.set(text.getText()); 
		}
	};
	
	public BindingTextBox(String header, TextDataSource dataSource)
	{
		super();
		this.dataSource = dataSource;
		setLayout(new BoxLayout(this,BoxLayout.X_AXIS));
		add(new JLabel(header));
		add(Box.createHorizontalGlue());
		text = new JTextField();
		text.setMaximumSize(new Dimension(500,25));
		text.setPreferredSize(new Dimension(500,25));
		if(dataSource.getDocument()!=null) text.setDocument(dataSource.getDocument());
		text.setText(dataSource.get());
		text.getDocument().addDocumentListener(documentChangeListener);
		add(text);
		
	}

	public void setEditable(boolean b){
		text.setEditable(b);
	}
	
	public void updateData(){
		update = true;
		text.setText(dataSource.get());
		update = false;
	}

}
